<!-- 回款列表 -->

<template>
  <div class="client-list">
    <pageHeader :title="title" :breadCrumb="breadCrumb" :show-back="true">
    </pageHeader>
    <div class="sales-order">
      <a-tabs v-model="getListType" @change="getSearchType" type="line">
        <a-tab-pane :key="3" title="全部汇款"> </a-tab-pane>
        <a-tab-pane :key="4" title="我的汇款"> </a-tab-pane>
      </a-tabs>
    </div>
    <div class="search-box">
      <div
        ><a-space
          ><a-input-search
            :style="{ width: '320px' }"
            v-model="NumberSearch"
            placeholder="请输入订单编号"
            search-button
            @change="Search" /></a-space
      ></div>

      <div>
        <a-space>
          <a-button type="outline" @click="reset">
            <template #icon> <icon-refresh /> </template>重置</a-button
          >
          <a-button status="warning">
            <template #icon>
              <icon-download />
            </template>
            <template #default>导入</template>
          </a-button>

          <a-button status="success">
            <template #icon>
              <icon-export rotate="-90" />
            </template>
            <template #default>导出</template>
          </a-button>

          <a-button type="primary" @click="showFormHeaderSetting"
            >表头设置</a-button
          >
        </a-space>
      </div>
    </div>
    <div style="padding: 10px">
      <TableTurn :table-data="getData" ref="tableRef">
        <a-table-column :width="80" align="center">
          <template #title> 序号 </template>
          <template #cell="{ rowIndex }">
            {{ rowIndex + 1 }}
          </template>
        </a-table-column>
        <a-table-column
          v-for="item in selectedHeader"
          :title="item.name"
          :data-index="item.code"
          :key="item.code"
          :width="200"
          align="center"
        >
          <!-- 计划开始时间 -->
          <template v-if="item.code === 'createdAt'" #cell="{ record }">
            {{ dayjs(record.createdAt).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
          <!-- 订单状态 -->
          <template v-else-if="item.code === 'okState'" #cell="{ record }">
            <div class="use-state">
              <div
                class="cycle"
                :class="
                  record.totalPrice === record.accumulatedCollectionPrice
                    ? 'greenColor-cycle'
                    : 'blueColor-cycle'
                "
              >
              </div>
              <div
                :class="
                  record.totalPrice === record.accumulatedCollectionPrice
                    ? 'greenColor'
                    : 'blueColor'
                "
                >{{
                  record.totalPrice === record.accumulatedCollectionPrice
                    ? '已完成'
                    : '执行中'
                }}</div
              >
            </div>
          </template>
        </a-table-column>
        <a-table-column align="center" :width="200" title="回款与发票详情">
          <template #cell="{ record }">
            <a-button type="text" @click="goDetail(record.id)"
              >查看详情</a-button
            >
          </template>
        </a-table-column>
        <a-table-column :width="300" fixed="right" title="操作" align="center">
          <template #title> 操作 </template>
          <template #cell="{ record }"
            ><a-button
              v-if="record.salesman === userInfo.id"
              type="text"
              @click="enter(record)"
              >付款录入</a-button
            >
            <a-button
              v-if="record.salesman === userInfo.id"
              type="text"
              @click="Invoice(record)"
              >发票录入</a-button
            >
          </template>
        </a-table-column>
      </TableTurn>
    </div>

    <FormHeaderSetting
      v-model:visible="formHeaderSettingVisible"
      title="回款列表表头设置"
      :resultList="headerSetting.list"
      @headerSave="headerSave"
    ></FormHeaderSetting>

    <returnedMoneyEnter
      v-model:visible="enterVisible"
      :currForm="currForm"
      :orderId="orderId"
      v-if="enterVisible"
      @editReturnedEmit="editReturnedEmit"
    ></returnedMoneyEnter>
    <invoiceInfo
      v-model:visible="invoiceVisible"
      :clientId="clientId"
      :orderId="orderId"
      :currForm="form"
      v-if="invoiceVisible"
      @editinvoiceInfo="editinvoiceInfo"
    ></invoiceInfo>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref, computed, defineAsyncComponent } from 'vue';
  import { useRouter } from 'vue-router';
  import { pageData as IpageData } from '@/types/global';
  import { formHeaderSetting } from '@/types/global';
  import dayjs from 'dayjs';
  import {
    getPurchaseHeader,
    PUTPurchaseHeader,
    getPurchaseOrderList,
    putSinglePurchaseOrder,
    delPurchaseOrderList,
  } from '@/api/buy-management/buy-order/index';
  import {
    postPurchaseOrderPay,
    postPurchaseOrderRecord,
  } from '@/api/buy-management/payment-management/index';

  let invoiceInfo = defineAsyncComponent(
    () => import('./components/invoice-information/index.vue')
  );

  let returnedMoneyEnter = defineAsyncComponent(
    () => import('./components/pay-money-enter/index.vue')
  );

  const router = useRouter();
  const title = '付款列表';
  const breadCrumb = ['采购管理', '付款管理', '付款列表'];
  const getListType = ref(3);
  const headerSetting = reactive<any>({
    list: [],
  });
  const NumberSearch = ref();
  let form = reactive({});
  const orderId = ref();
  const clientId = ref();
  const invoiceVisible = ref(false);
  let enterVisible = ref(false); // 判断用户是否点击录入按钮

  const userInfo = JSON.parse(sessionStorage.getItem('loginInfo') as any);

  let tableRef = ref(); // 储存table的ref

  // 获取回款列表数据
  const getData = async (pageData?: any) => {
    const msg: any = {};
    if (NumberSearch.value) msg.number = NumberSearch.value;
    const res = await getPurchaseOrderList({ ...pageData, payList: 1, ...msg });
    return Promise.resolve(res);
  };

  const columns = [
    {
      name: '订单编号',
      code: 'number',
      isDefault: 1,
    },
    {
      name: '供应商名称',
      code: 'supplierName',
      isDefault: 1,
    },
    {
      name: '采购员',
      code: 'userStaffName',
      isDefault: 1,
    },
    {
      name: '订单总金额',
      code: 'totalPrice',
      isDefault: 1,
    },
    {
      name: '订单创建时间',
      code: 'createdAt',
      isDefault: 1,
    },
    {
      name: '应付账款总额',
      code: 'needPayPrice',
      isDefault: 1,
    },
    {
      name: '累计付款金额',
      code: 'accumulatedPayPrice',
      isDefault: 1,
    },
    {
      name: '未付款金额',
      code: 'waitPayPrice',
      isDefault: 1,
    },
    {
      name: '已开票金额',
      code: 'invoicedPrice',
      isDefault: 1,
    },
    {
      name: '可开票金额',
      code: 'invoicablePrice',
      isDefault: 1,
    },
    {
      name: '订单状态',
      code: 'okState',
      isDefault: 1,
    },
  ];

  const formHeaderSettingVisible = ref();
  const showFormHeaderSetting = () => {
    formHeaderSettingVisible.value = true;
  };
  // 获取表头设置
  const headerSettingData = async () => {
    try {
      const res = await getPurchaseHeader({ userId: 317, listType: 7 });

      headerSetting.list = res.extends ? res.extends : columns;
    } catch (err: unknown) {
      console.log(err);
    }
  };
  headerSettingData();

  // 在表格上显示的表头
  const selectedHeader = computed(() => {
    const arr: any = [];
    columns.forEach((item) => {
      if (item.isDefault === 1) {
        arr.push(item);
      }
    });
    return arr;
  });

  // 表头设置保存后返回的自定义事件
  const headerSave = async (val) => {
    try {
      const data = {
        userId: 317,
        listType: 7,
        extend: JSON.stringify(val),
      };
      await PUTPurchaseHeader(data);
      headerSetting.list = [...val];
    } catch (err: unknown) {
      console.log(err);
    }
  };

  const currForm = ref();

  // 录入按钮事件
  const enter = (record?: any) => {
    currForm.value = record;
    orderId.value = record.id;

    enterVisible.value = true;
  };

  // 录入按钮返回来的自定义事件
  const editReturnedEmit = async (formData: any) => {
    let msg = ref(JSON.parse(JSON.stringify(formData)));
    msg.value.orderId = msg.value.id;
    msg.value.payTime = new Date(msg.value.payTime).toJSON();
    msg.value.number = msg.value.payNumber;
    delete msg.value.id;
    await postPurchaseOrderPay({
      ...msg.value,
    });
    tableRef.value.loadData();
  };

  const Invoice = (record: any) => {
    invoiceVisible.value = true;
    clientId.value = record.clientCompanyId;
    form = {
      orderId: undefined, //订单id
      collectionTypeId: undefined, //回款类型id
      invoiceNumber: '', //发票编号
      InvoiceTypeId: undefined, //发票类型Id
      invoicingTime: undefined, //开票时间
      invoicingPrice: undefined, //开票金额
      invoicingPriceUnit: '', //开票金额单位
      invoicingSubject: '', //开票科目
      invoicingUserId: undefined, //开票人
      invoiceMessageId: undefined, //发票凭证文件id
      invoiceProofFileId: undefined, //订单id
      TaxRate: '',
    };
    orderId.value = record.id;
  };

  const editinvoiceInfo = async (formData: any) => {
    formData.number = formData.invoiceNumber;
    await postPurchaseOrderRecord({ ...formData });
    tableRef.value.loadData();
  };

  // 查看详情按钮
  const goDetail = (id: any) => {
    router.push({
      name: 'PaymentDetail',
      query: {
        id,
      },
    });
  };

  const Search = () => {
    tableRef.value.loadData();
  };

  // 重置按钮
  const reset = () => {
    NumberSearch.value = '';
    tableRef.value.loadData();
  };
</script>

<style scoped lang="less">
  .search-box {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    padding: 0px 10px;
  }

  :deep(.arco-space-item) {
    margin-top: 10px;
  }
  .use-state {
    display: flex;
    justify-content: center;
    text-align: center;
  }
  .cycle {
    position: relative;
    width: 16px;
    height: 16px;
    border-radius: 50%;
    content: '';
    display: inline-block;
    top: 3px;
    right: 10px;
  }

  .blueColor {
    color: #156dff;
  }
  .blueColor-cycle {
    background-color: #156dff;
  }
  // 已通过
  .greenColor {
    color: #31c273;
  }
  .greenColor-cycle {
    background-color: #31c273;
  }

  :deep(.arco-tabs-content) {
    padding-top: 0px;
  }
</style>
